package message

import (
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
	"github.com/go-gomail/gomail"
	"log"
)

type EmailInfo struct {
	ServerHost string // ServerHost 邮箱服务器地址，如腾讯企业邮箱为smtp.exmail.qq.com
	ServerPort int    // ServerPort 邮箱服务器端口，如腾讯企业邮箱为465

	FromEmail  string // FromEmail　发件人邮箱地址
	FromPasswd string //发件人邮箱密码（注意，这里是明文形式)

	Recipient []string //收件人邮箱
	CC        []string //抄送
}

var emailMessage *gomail.Message

func SendEmail(subject, body string, emailInfo *EmailInfo) {
	if len(emailInfo.Recipient) == 0 {
		log.Print("收件人列表为空")
		return
	}

	emailMessage = gomail.NewMessage()
	//设置收件人
	emailMessage.SetHeader("To", emailInfo.Recipient...)
	//设置抄送列表
	if len(emailInfo.CC) != 0 {
		emailMessage.SetHeader("Cc", emailInfo.CC...)
	}
	// 第三个参数为发件人别名，如"dcj"，可以为空（此时则为邮箱名称）
	emailMessage.SetAddressHeader("From", emailInfo.FromEmail,
		web.AppConfig.DefaultString("EmailName", "rate"))

	//主题
	emailMessage.SetHeader("Subject", subject)

	//正文
	emailMessage.SetBody("text/html", body)

	d := gomail.NewPlainDialer(emailInfo.ServerHost, emailInfo.ServerPort,
		emailInfo.FromEmail, emailInfo.FromPasswd)
	err := d.DialAndSend(emailMessage)
	if err != nil {
		logs.Error("发送邮件失败： ", err)
	} else {
		logs.Info("已成功发送邮件到指定邮箱")
	}
}

// SendRegister 发送注册邮件
func SendRegister(code, email string) {
	recList := []string{email} //收件人邮箱地址

	info := &EmailInfo{
		web.AppConfig.DefaultString("EmailSMTP", ""),
		web.AppConfig.DefaultInt("EmailPort", 25),
		web.AppConfig.DefaultString("Email", ""), //发件人邮箱地址
		web.AppConfig.DefaultString("EmailSecret", ""),
		recList,
		nil,
	}
	subject := "【唠梨穿透】会员注册"
	body := fmt.Sprintf("<h3>亲，您正在注册唠梨会员，这是您的验证码：</h3><p>%s</p>", code)
	go SendEmail(subject, body, info)
}
